/*
 * @Descripttion: 
 * @version: 
 * @Author: TT
 * @Date: 2022-12-05 14:58:16
 * @LastEditors: TT
 * @LastEditTime: 2023-03-01 21:51:45
 */

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:hzy_normal_widget/hzy_normal_utils.dart';
import 'package:hzy_normal_widget/hzy_normal_widget.dart';
import 'common_extendeed_image_widget.dart';
import 'common_state_widget.dart';
// ignore: depend_on_referenced_packages
import 'package:extended_image_library/extended_image_library.dart';

class ImageNormalModel {
  Size? imageSize;
  String imageeUrl;
  ImageNormalModel({required this.imageeUrl, this.imageSize});
}

class CommonLongGraphPage extends StatefulWidget {
  final List<File>? list;
  final List<Uint8List>? bytelist;
  final List<String>? imageurllist;
  final Function(int index)? scrollerindex;
  final Function(int index)? ontap;
  final bool? keepAlive;
  final String? heroStr;
  final int? index;
  final bool? cache;
  final List<ImageNormalModel>? imageModellist;
  final String? cachename;
  const CommonLongGraphPage({
    Key? key,
    this.list,
    this.bytelist,
    this.scrollerindex,
    this.ontap,
    this.keepAlive,
    this.heroStr,
    this.imageurllist,
    this.index,
    this.cachename,
    this.imageModellist,
    this.cache = true,
  }) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return CommonLongGraphPageState();
  }
}

class CommonLongGraphPageState extends CommonStateWidget<CommonLongGraphPage>
    with AutomaticKeepAliveClientMixin {
  /// 属性
  ///
  ///
  @override
  bool get safeAreabottm => false;
  @override
  bool get safeAreatop => false;
  @override
  Color? get backgroundColor => const Color(0xff181818);
  double maxh = 0;
  ScrollController scrollController = ScrollController(initialScrollOffset: 0);
  int num = 0;
  double bgheight = 0;
  List<Widget> list = [];

  int normalindex = 0;

  /// 生命周期
  ///
  ///

  /// 界面初始化
  @override
  void initDefaultState() {
    list = createListImage();
    scrollController = ScrollController(
      initialScrollOffset: configScrollerJumpToHeight(
        index: widget.index ?? 0,
      ),
    );
    super.initDefaultState();
  }

  /// 界面销毁
  @override
  void initDefaultDispose() {
    scrollController.dispose();
    super.initDefaultDispose();
  }

  /// 网路请求
  ///
  ///

  /// 构建视图
  ///
  ///

  @override
  Widget build(BuildContext context) {
    super.build(context);

    return createScaffol(
      context: context,
      safeAreatop: safeAreatop,
      safeAreabottm: safeAreabottm,
      pageState: pageState,
      title: title,
      backgroundColor: backgroundColor,
      navbackcolor: navbackcolor,
      resizeToAvoidBottomInset: resizeToAvoidBottomInset,
    );
  }

  @override
  Widget createBody(BuildContext context) {
    return LayoutBuilder(
      builder: (p0, p1) {
        bgheight = p1.maxHeight;
        return createScrollWidget();
      },
    );
  }

  // 创建滚动视图
  createScrollWidget() {
    NotificationListener<ScrollNotification> s =
        NotificationListener<ScrollNotification>(
      onNotification: (ScrollNotification notification) {
        if (notification.metrics.maxScrollExtent > 0 &&
            notification.metrics.pixels > 0) {
          double progress = notification.metrics.pixels /
              notification.metrics.maxScrollExtent;

          if (progress <= 1 && progress >= 0) {
            // if (widget.imageModellist != null) {
            //   configImageModelNotificationListener(
            //       pixels: notification.metrics.pixels);
            // } else {
            maxh = notification.metrics.maxScrollExtent;
            int index = (num * progress).truncate();
            if (index >= num) {
              index = num - 1;
            }
            if (widget.scrollerindex != null && index != normalindex) {
              normalindex = index;
              debugprint(progress);
              widget.scrollerindex!(index);
            }
            // }
          }
        }
        return false;
      },
      child: SingleChildScrollView(
        controller: scrollController,
        child: Column(
          children: list,
        ),
      ),
    );
    return s;
  }

  // 创建图片数组
  createListImage() {
    List<Widget> list = [];
    num = widget.bytelist?.length ??
        (widget.list?.length ??
            (widget.imageurllist?.length ??
                (widget.imageModellist?.length ?? 0)));

    for (var i = 0; i < num; i++) {
      list.add(createItemBuilder(context, i));
    }
    debugprint("图拍的整体高度$maxh");
    return list;
  }

  // 创建单个图片
  Widget createItemBuilder(BuildContext context, int index) {
    String? herostr = widget.heroStr == null ? null : "${widget.heroStr}";
    Widget child = Container();
    double? width;
    double? height;
    String? imageurl = widget.imageurllist?[index];
    if (widget.imageModellist != null) {
      ImageNormalModel? imageModel = widget.imageModellist?[index];
      imageurl = imageModel?.imageeUrl;

      width = imageModel?.imageSize?.width;
      height = imageModel?.imageSize?.height;
    }
    maxh = maxh + (height ?? 0);
    child = ExtendedImageWidget.createbannerimage(
      herostr: "$herostr$index",
      bytes: widget.bytelist?[index],
      imagefile: widget.list?[index],
      imageurl: imageurl,
      cache: widget.cache,
      width: width,
      height: height,
      imageCacheName: widget.cachename,
    );
    if (widget.ontap != null) {
      child = InkWell(
        child: child,
        onTap: () {
          widget.ontap!(index);
        },
      );
    }

    return child;
  }

  /// 触发方法
  ///
  ///
  ///

  /// 配置默认数据

  configImageModelNotificationListener({required double pixels}) {
    double jumptoheight = 0;
    int index = 0;
    for (var i = 0; i < num; i++) {
      ImageNormalModel imageNormalModel = widget.imageModellist![i];
      jumptoheight = jumptoheight + (imageNormalModel.imageSize?.height ?? 0);
      if (jumptoheight > pixels) {
        index = i;
        break;
      }
    }
    if (index == num - 2) {
      ImageNormalModel imageNormalModel = widget.imageModellist!.last;
      if ((imageNormalModel.imageSize?.height ?? 0) < bgheight) {}
      if (pixels == maxh - bgheight) {
        index = num - 1;
      }
    }
    if (widget.scrollerindex != null) {
      widget.scrollerindex!(index);
    }
  }

  /// 对外公开 配置滚动距离
  void changescrollerindex(int index) {
    if (maxh == 0 || index == normalindex) {
      return;
    }

    double jumph = 0;
    if (index == (num - 1)) {
      if (widget.imageModellist != null) {
        ImageNormalModel imageNormalModel = widget.imageModellist!.last;
        if ((imageNormalModel.imageSize?.height ?? 0) < bgheight) {
          jumph = maxh - bgheight;
        } else {
          jumph = maxh;
        }
      } else {
        jumph = maxh;
      }
    } else {
      // if (widget.imageModellist != null) {
      //   jumph = configScrollerJumpToHeight(index: index);
      // } else {
      jumph = (index / num) * maxh;
      // }
    }

    scrollController.jumpTo(jumph);
  }

  /// 根据图片 大小  获取 滚动距离
  configScrollerJumpToHeight({
    required int index,
  }) {
    double jumptoheight = 0;
    for (var i = 0; i < index; i++) {
      ImageNormalModel imageNormalModel = widget.imageModellist![i];
      jumptoheight = jumptoheight + (imageNormalModel.imageSize?.height ?? 0);
    }
    int currentindex = index - 1;
    if (currentindex < 0) {
      currentindex = 0;
    }
    ImageNormalModel imageNormalModel = widget.imageModellist![currentindex];
    double indexHeight = imageNormalModel.imageSize?.height ?? 0;
    double cj = maxh - jumptoheight;
    if (cj < bgheight) {
      jumptoheight = jumptoheight - indexHeight - bgheight;
    }
    return jumptoheight;
  }

  void reloadState() {
    configsetState(() {});
  }

  @override
  bool get wantKeepAlive => (widget.keepAlive ?? true);
}
